import React, { useEffect, useState } from 'react';
import './ProjectManagement.css';
import { Project, ProjectMember } from '../../services/project';
import * as projectService from '../../services/project';

const ProjectManagement: React.FC = () => {
  const [projects, setProjects] = useState<Project[]>([]);
  const [selectedProject, setSelectedProject] = useState<Project | null>(null);
  const [projectMembers, setProjectMembers] = useState<ProjectMember[]>([]);
  const [loading, setLoading] = useState(false);
  const [showProjectForm, setShowProjectForm] = useState(false);
  const [currentProject, setCurrentProject] = useState<Partial<Project> & { id?: number }>({
    name: '',
    description: '',
    status: 1,
    remark: ''
  });

  // 获取项目列表
  const fetchProjects = async () => {
    setLoading(true);
    try {
      const response = await projectService.listProjects();
      if (response.success) {
        setProjects(response.data);
      }
    } catch (error) {
      console.error('获取项目列表失败:', error);
    } finally {
      setLoading(false);
    }
  };

  // 获取项目成员列表
  const fetchProjectMembers = async (projectId: number) => {
    try {
      const response = await projectService.listProjectMembers(projectId);
      if (response.success) {
        setProjectMembers(response.data);
      }
    } catch (error) {
      console.error('获取项目成员列表失败:', error);
    }
  };

  // 创建或更新项目
  const saveProject = async () => {
    try {
      let response;
      if (currentProject.id) {
        // 更新项目
        const { id, ...updateData } = currentProject;
        response = await projectService.updateProject(id!, updateData);
      } else {
        // 创建项目 - 只传递必要的字段
        const newProject: Partial<Project> = {
          name: currentProject.name || '',
          description: currentProject.description || '',
          status: currentProject.status || 1,
          remark: currentProject.remark || ''
        };
        response = await projectService.createProject(newProject as Omit<Project, 'id'>);
      }
      
      if (response.success) {
        // 重置表单并刷新列表
        setShowProjectForm(false);
        setCurrentProject({
          name: '',
          description: '',
          status: 1,
          remark: ''
        });
        fetchProjects();
      }
    } catch (error) {
      console.error('保存项目失败:', error);
    }
  };

  // 删除项目
  const deleteProject = async (id: number) => {
    try {
      const response = await projectService.deleteProject(id);
      if (response.success) {
        // 刷新列表
        fetchProjects();
        // 如果删除的是当前选中的项目，清空选中状态
        if (selectedProject && selectedProject.id === id) {
          setSelectedProject(null);
          setProjectMembers([]);
        }
      }
    } catch (error) {
      console.error('删除项目失败:', error);
    }
  };

  // 删除项目成员
  const removeProjectMember = async (memberId: number) => {
    if (!selectedProject) return;
    
    try {
      const response = await projectService.removeProjectMember(selectedProject.id, memberId);
      if (response.success) {
        // 刷新成员列表
        fetchProjectMembers(selectedProject.id);
      }
    } catch (error) {
      console.error('删除项目成员失败:', error);
    }
  };

  // 处理项目选择
  const handleSelectProject = (project: Project) => {
    setSelectedProject(project);
    fetchProjectMembers(project.id);
  };

  // 处理编辑项目
  const handleEditProject = (project: Project) => {
    setCurrentProject({
      id: project.id,
      name: project.name,
      description: project.description,
      status: project.status,
      remark: project.remark
    });
    setShowProjectForm(true);
  };

  // 处理新建项目
  const handleCreateProject = () => {
    setCurrentProject({
      name: '',
      description: '',
      status: 1,
      remark: ''
    });
    setShowProjectForm(true);
  };

  useEffect(() => {
    fetchProjects();
  }, []);

  return (
    <div className="project-management">
      <h1>项目管理</h1>
      
      <div className="project-management-content">
        {/* 项目列表 */}
        <div className="project-list">
          <div className="project-list-header">
            <h2>项目列表</h2>
            <button onClick={handleCreateProject}>创建项目</button>
          </div>
          
          {loading ? (
            <div>加载中...</div>
          ) : (
            <ul className="project-items">
              {projects.map(project => (
                <li 
                  key={project.id} 
                  className={`project-item ${selectedProject?.id === project.id ? 'selected' : ''}`}
                  onClick={() => handleSelectProject(project)}
                >
                  <div className="project-info">
                    <h3>{project.name}</h3>
                    <p>{project.description}</p>
                  </div>
                  <div className="project-actions">
                    <button onClick={(e) => {
                      e.stopPropagation();
                      handleEditProject(project);
                    }}>
                      编辑
                    </button>
                    <button onClick={(e) => {
                      e.stopPropagation();
                      deleteProject(project.id);
                    }}>
                      删除
                    </button>
                  </div>
                </li>
              ))}
            </ul>
          )}
        </div>
        
        {/* 项目详情和成员管理 */}
        <div className="project-detail">
          {selectedProject ? (
            <>
              <div className="project-detail-header">
                <h2>{selectedProject.name}</h2>
                <p>{selectedProject.description}</p>
              </div>
              
              <div className="project-members">
                <div className="project-members-header">
                  <h3>项目成员</h3>
                  <button>添加成员</button>
                </div>
                
                <ul className="member-list">
                  {projectMembers.map(member => (
                    <li key={member.id} className="member-item">
                      <div className="member-info">
                        <span>用户ID: {member.userId}</span>
                        <span>角色: {member.role}</span>
                      </div>
                      <div className="member-actions">
                        <button>编辑</button>
                        <button onClick={() => removeProjectMember(member.id)}>移除</button>
                      </div>
                    </li>
                  ))}
                </ul>
              </div>
            </>
          ) : (
            <div className="no-project-selected">
              <p>请选择一个项目</p>
            </div>
          )}
        </div>
      </div>
      
      {/* 项目表单模态框 */}
      {showProjectForm && (
        <div className="project-form-modal">
          <div className="project-form-content">
            <h2>{currentProject.id ? '编辑项目' : '创建项目'}</h2>
            <form onSubmit={(e) => {
              e.preventDefault();
              saveProject();
            }}>
              <div className="form-group">
                <label htmlFor="projectName">项目名称</label>
                <input
                  type="text"
                  id="projectName"
                  value={currentProject.name || ''}
                  onChange={(e) => setCurrentProject({...currentProject, name: e.target.value})}
                  required
                />
              </div>
              
              <div className="form-group">
                <label htmlFor="projectDescription">项目描述</label>
                <textarea
                  id="projectDescription"
                  value={currentProject.description || ''}
                  onChange={(e) => setCurrentProject({...currentProject, description: e.target.value})}
                />
              </div>
              
              <div className="form-actions">
                <button type="button" onClick={() => setShowProjectForm(false)}>取消</button>
                <button type="submit">保存</button>
              </div>
            </form>
          </div>
        </div>
      )}
    </div>
  );
};

export default ProjectManagement;